package com.ceuer.pet.dao.impl;

import com.ceuer.pet.dao.BreedDao;
import com.ceuer.pet.entity.Breed;
import com.ceuer.pet.entity.Species;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class BreedDaoImpl extends BaseDao implements BreedDao {
	
	@Override
	public List<Breed> selectAll(Integer speciesid) {
		List<Breed> list= new ArrayList<>();
		Connection connection=null;
		PreparedStatement preparedStatement=null;
		ResultSet resultSet=null;
		try {
			String sql="select b.id,b.name,s.id speciesid,s.name speciesname from breed b,species s where b.speciesid=s.id and s.id=?";
			connection=this.getConn();
			preparedStatement=connection.prepareStatement(sql);
			preparedStatement.setInt(1, speciesid);
			resultSet=preparedStatement.executeQuery();
			while (resultSet.next()){
				Breed breed = new Breed();
				Species species = new Species();
				breed.setId(resultSet.getInt("id"));
				breed.setName(resultSet.getString("name"));
				species.setId(resultSet.getInt("speciesid"));
				species.setName(resultSet.getString("speciesname"));
				breed.setSpecies(species);
				
				list.add(breed);
			}
		}catch (Exception e){
			e.printStackTrace();
		}finally {
			this.closeAll(connection, preparedStatement, resultSet);
		}
		return list;
	}
	
	@Override
	public Breed selectOne(Integer id) {
		Breed breed=null;
		Connection connection=null;
		PreparedStatement preparedStatement=null;
		ResultSet resultSet=null;
		try {
			String sql="select b.id,b.name,s.id speciesid,s.name speciesname from breed b,species s where b.speciesid=s.id and b.id=?";
			connection=this.getConn();
			preparedStatement=connection.prepareStatement(sql);
			preparedStatement.setInt(1, id);
			resultSet=preparedStatement.executeQuery();
			while (resultSet.next()){
				breed = new Breed();
				Species species = new Species();
				breed.setId(resultSet.getInt("id"));
				breed.setName(resultSet.getString("name"));
				species.setId(resultSet.getInt("speciesid"));
				species.setName(resultSet.getString("speciesname"));
				breed.setSpecies(species);
			}
		}catch (Exception e){
			e.printStackTrace();
		}finally {
			this.closeAll(connection, preparedStatement, resultSet);
		}
		return breed;
	}
	
	@Override
	public boolean add(Breed breed) {
		String sql="insert into breed(speciesid,name) values (?,?)";
		List<Object> param=new ArrayList<>();
		param.add(breed.getSpecies().getId());
		param.add(breed.getName());
		int num=this.executeUpdate(sql,param);
		return num==1;
	}
	
	@Override
	public boolean update(Breed breed) {
		String sql="update breed set speciesid=?,name=? where id=?";
		List<Object> param=new ArrayList<>();
		param.add(breed.getSpecies().getId());
		param.add(breed.getName());
		param.add(breed.getId());
		int num=this.executeUpdate(sql,param);
		return num==1;
	}
}